<?php

namespace Beerus\Modules\Brand\Controllers;

use App\Http\Controllers\Controller;
use Biz\model\brand\Brand as mBrand;
use Biz\model\brand\BrandOrder;
use Biz\model\brand\BrandPackage;
use Biz\model\brand\BrandStub as mBrandStub;
use Biz\model\brandAccount\BrandAccountInfo;
use Biz\model\trade\OrderPay;
use Biz\service\brand\BrandService;
use Biz\service\brand\Order;
use Biz\service\brand\OrderSN;
use Biz\service\brandAccount\BrandAccount;
use Biz\service\brandPack\RenewPackageService;
use Biz\service\BrandRights\BrandRightsAllService;
use Doraemon\model\ImageCreate\ImageCreate as mImageCreate;
use Doraemon\model\Member as mMember;
use Doraemon\service\Favorite;
use Doraemon\tools\ImageCreate;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

/**
 * 品牌升级：设置精选品牌、超级品牌
 *
 * @category   Module name
 * @package    PSR
 * @subpackage Documentation\API
 * @author     zhouyang  <zhouyang@haohaozhu.com>
 * @license    GPL http://www.haohaozhu.com
 * @link       http://www.haohaozhu.com
 */
class BrandUpgradeController extends Controller
{
    const PAGE_SIZE = 20;

    // 品牌身份
    const BRAND_TYPE = [
        1 => '到期品牌',
        2 => '认证品牌',
        3 => '精选品牌',
        4 => '超级品牌',
    ];

    // 操作精选、超级品牌
    const OP_BRAND_BEST = 1;
    const OP_BRAND_SUPER = 2;

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    public function addOrder(Request $request, Content $content, $id)
    {
        //todo 补差价计算
        $request = $request->all();
        $info = BrandAccountInfo::getOneByWhere(['id' => $id]);
        $uid = $info['uid'];
        $hasUnUsedOrderRes = BrandOrder::hasUnUsedOrder($uid);
        $hasUnUsedOrder = $hasUnUsedOrderRes[$uid];
        if ($hasUnUsedOrder) {
            admin_toastr('该品牌已存在未生效的续费订单，无法再次续费和升级。', 'warning', ['timeOut' => 5000, 'positionClass' => 'toast-bottom-right']);
            return back()->with();
        }
        // 查询用户是否有未开启服务的订单
        $order = BrandOrder::get('*', [
            'uid' => $info['uid'],
            'brand_id' => $info['brand_id'],
            'pay_status' => BrandOrder::PAY_STATUS_PAID,
            'service_status' => BrandOrder::SERVICE_STATUS_UNFINISHED
        ]);
        if (!empty($order)) {
            admin_toastr('有未完成的订单', 'warning', ['timeOut' => 5000, 'positionClass' => 'toast-bottom-right']);
            return back()->with();
        }
        $info['idea'] = Favorite::getCounterByPhoto($info['uid']);

        $shopWikiNum = \Biz\service\brandAccount\BrandAccount::getAccountShopWikiCount($info['id']);
        $info['goods_num'] = $shopWikiNum;

        $hasOrder = BrandOrder::hasOrder($info['brand_id']);
        $info['has_order'] = (int)$hasOrder;
        $memberUid = mMember::getUidByNick($info['nick']);
        $brandInfo = mBrand::getInfo($info['brand_id']);
        $info['pack_type'] = $brandInfo['pack_type'];
        $info['pack_type_desc'] = isset(BrandPackage::$packTypeDesc[$brandInfo['pack_type']]) ? BrandPackage::$packTypeDesc[$brandInfo['pack_type']] : '无';
        //新开默认时间
        $startTime1 = date('Y-m-d');
        $info['in_start_time1'] = $startTime1;
        $info['in_end_time1'] = date('Y-m-d', strtotime('+365day', strtotime($startTime1)));
        $info['pack_type1'] = $info['pack_type'];
        $info['identify1'] = $info['identify'];
        //升级默认时间
        $startTime2 = strtotime($info['in_start_time']) > 0 ? $info['in_start_time'] : date('Y-m-d');
        $endTime2 = strtotime($info['in_end_time']) > 0 ? $info['in_end_time'] : date('Y-m-d', strtotime('+365day', strtotime($startTime2)));
        $info['in_start_time2'] = $startTime2;
        $info['in_end_time2'] = $endTime2;
        $info['pack_type2'] = $info['pack_type'];
        $info['identify2'] = $info['identify'];
        //续签默认时间
        $startTime3 = strtotime($info['in_end_time']) > 0 ? date('Y-m-d', strtotime('+1day', strtotime($info['in_end_time']))) : date('Y-m-d');
        $info['in_start_time3'] = $startTime3;
        $info['in_end_time3'] = date('Y-m-d', strtotime('+365day', strtotime($startTime3)));
        $info['pack_type3'] = $info['pack_type'];
        $info['identify3'] = $info['identify'];

        $form = new Form($info);
        $form->hidden('id');
        $form->hidden('uid');
        $form->hidden('status');
        $form->text('id', '账户id')->disable()->setWidth(4, 2);
        $form->text('uid', '账户uid')->disable()->setWidth(4, 2);
        $form->text('brand_id', '品牌id')->readOnly()->setWidth(4, 2);
        $form->text('nick', $memberUid && $memberUid != $info['uid'] ? '账户认证昵称 [昵称已被使用,请修改!!!]' : '账户认证昵称')
            ->setWidth(4, 2)->readOnly();
        $form->date('auth_start_time', '认证起始时间')->setWidth(4, 2)->readOnly();
        $form->date('letter_time', '认证到期时间')->setWidth(4, 2)->readOnly();
        $form->select('has_order', '是否产生过订单')->setWidth(4, 2)->options([0 => '否', 1 => '是'])->disable();
        $form->text('pack_type_desc', '当前套餐')->disable()->setWidth(4, 2);
        $defaultOrderType = $this->getDefaultOrderType($info);
        $whenOption = $this->getWhenOption($defaultOrderType);
        $form->select('order_type', '订单类型')->options(
            $whenOption
        )->when(BrandOrder::ORDER_TYPE_NEW, function (Form $form) use ($info) {
            $form->date('in_start_time1', '入驻开始时间')->setWidth(4, 2)->help("<span style='color: #ff0000'>请检查时间，必填</span>");
            $form->date('in_end_time1', '入驻到期时间')->setWidth(4, 2)->help("<span style='color: #ff0000'>请检查时间，必填</span>");
            $option = BrandService::getPackageOption($info['brand_id'], $info['pack_type']);
            $help = [
                '认证账号、认证套餐：为认证账号的套餐。',
                '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;高级认证账号、高级认证简单套餐、高级认证套餐：为高级认证账号的套餐。',
            ];
            $form->select('pack_type1', '套餐')->options($option)->setWidth(6, 2)->help("<span style='color: #ff0000'>" . implode('<br/>', $help) . "</span>");;
            $form->text('identify1', '标识')->options($option)->setWidth(4, 2)->help("<span style='color: #ff0000'>必填</span>");
        })->when(BrandOrder::ORDER_TYPE_UPGRADE, function (Form $form) use ($info) {
            $form->date('in_start_time2', '入驻开始时间')->setWidth(4, 2)->required('不能为空')->help("<span style='color: #ff0000'>请检查时间，必填</span>")->readonly();
            $form->date('in_end_time2', '入驻到期时间')->setWidth(4, 2)->required('不能为空')->help("<span style='color: #ff0000'>请检查时间，必填</span>")->readonly();
            $option = BrandService::getPackageOption($info['brand_id'], $info['pack_type']);
            $help = [
                '认证账号、认证套餐：为认证账号的套餐。',
                '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;高级认证账号、高级认证简单套餐、高级认证套餐：为高级认证账号的套餐。',
            ];
            $form->select('pack_type2', '套餐')->options($option)->setWidth(6, 2)->help("<span style='color: #ff0000'>" . implode('<br/>', $help) . "</span>");;
            $form->text('identify2', '标识')->options($option)->setWidth(4, 2)->help("<span style='color: #ff0000'>必填</span>");
        })->when(BrandOrder::ORDER_TYPE_RENEW, function (Form $form) use ($info) {
            $form->date('in_start_time3', '入驻开始时间')->setWidth(4, 2)->help("<span style='color: #ff0000'>请检查时间，必填</span>");
            $form->date('in_end_time3', '入驻到期时间')->setWidth(4, 2)->help("<span style='color: #ff0000'>请检查时间，必填</span>");
            $option = BrandService::getPackageOption($info['brand_id'], 0);
            $help = [
                '认证账号、认证套餐：为认证账号的套餐。',
                '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;高级认证账号、高级认证简单套餐、高级认证套餐：为高级认证账号的套餐。',
            ];
            $form->select('pack_type3', '套餐')->options($option)->setWidth(6, 2)->help("<span style='color: #ff0000'>" . implode('<br/>', $help) . "</span>");;
            $form->text('identify3', '标识')->options($option)->setWidth(4, 2)->help("<span style='color: #ff0000'>必填</span>");;
        })->setWidth(4)->default($defaultOrderType)->help("<span style='color: red'>请选择订单类型（开通、升级、续费）</span>");;
        $help = [
            '开通套餐：请参考套餐价格。',
            '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;升级套餐：(升级套餐-当前套餐)/365*(品牌到期时间-升级时间)；金额取整。',
        ];
        $form->decimal('amount', '支付金额')->setWidth(6, 2)->help("<span style='color: #ff0000'>" . implode('<br/>', $help) . "</span>")->required();
        $form->select('pay_platform', '付款类型')->options(mBrandStub::PAY_PLATFORM)->setWidth(2, 2)->required();;
        $form->text('other_sn', '交易流水号')->setWidth(4, 2)->required('不能为空');
        $form->imgUpload('trade_proof', '交易凭证')->help("<span style='color: red'>交易凭证必传</span>");
        $form->action('/admin/brand/upgrade/order/' . $id . '/save');
        return $content
            ->header('添加付费订单')
            ->breadcrumb(
                ['text' => '品牌账户管理 ', 'url' => '/brand/account/index'],
                ['text' => '添加付费订单'],
            )
            ->body($form->render());
    }

    public function saveOrder(Request $request, Content $content, $id)
    {
        try {
            $brand_account = BrandAccountInfo::getOneByWhere(['id' => $id]);
            if (empty($brand_account)) {
                throw new \Exception('品牌账户不存在');
            }
            if (empty($brand_account['uid'])) {
                throw new \Exception('请先给品牌绑定一个用户');
            }
            $request = $request->all();
            $orderType = $request['order_type'];
            if (empty($orderType) || !isset(BrandOrder::ORDER_TYPE_MAP[$orderType])) {
                throw new \Exception('请选择订单类型');
            }
            if ($orderType == 1) {
                $inStartTime = $request['in_start_time1'];
                $inEndTime = $request['in_end_time1'];
                $packType = $request['pack_type1'];
                $identify = $request['identify1'];
            } else if ($orderType == 2) {
                $inStartTime = $request['in_start_time2'];
                $inEndTime = $request['in_end_time2'];
                $packType = $request['pack_type2'];
                $identify = $request['identify2'];
            } else if ($orderType == 3) {
                $inStartTime = $request['in_start_time3'];
                $inEndTime = $request['in_end_time3'];
                $packType = $request['pack_type3'];
                $identify = $request['identify3'];
            }
            if (empty($request['trade_proof'])) {
                throw new \Exception('请上传交易凭证');
            }
            if (empty($identify)) {
                throw new \Exception('请输入订单标识');
            }
            if (empty($request['pay_platform'])) {
                throw new \Exception('请选择付款类型');
            }
            if (empty($inEndTime)) {
                throw new \Exception('请输入入驻结束时间');
            }
            if (empty($inStartTime) || empty($inEndTime)) {
                throw new \Exception('请选择入驻时间');
            }
            if (strtotime($inStartTime) >= strtotime($inEndTime)) {
                throw new \Exception('入驻结束时间必须大于入驻开始时间');
            }
            if ($orderType == 1 || $orderType == 3) {
                if (strtotime($inStartTime) < strtotime(date('Y-m-d'))) {
                    throw new \Exception('入驻开始时间不能小于当前时间');
                }
                if (strtotime($inEndTime) < strtotime(date('Y-m-d'))) {
                    throw new \Exception('入驻结束时间不能小于等于当前时间');
                }
            }
            $packArr = [];
            if ($packType < BrandPackage::NEW_PACK_TYPE_START) {
                $isNewPack = BrandService::isNewPack($packType);
                $packArr = $isNewPack ? BrandPackage::$newPackTypeList : BrandPackage::$packTypeList;
            } else {
                $newCreatedPackages = BrandPackage::getNewCreatedPackage();
                if ($newCreatedPackages) {
                    $packArr = array_filter(array_unique(array_column($newCreatedPackages, 'pack_type')));
                }
            }
            if (empty($packType) || !in_array($packType, $packArr)) {
                throw new \Exception('请选择一个套餐');
            }

            switch ($orderType) {
                case BrandOrder::ORDER_TYPE_NEW:
                    break;
                case BrandOrder::ORDER_TYPE_UPGRADE:
                    if ($inStartTime != $brand_account['in_start_time'] || $inEndTime != $brand_account['in_end_time']) {
                        throw new \Exception('升级套餐的入驻时间和当前套餐时间必须一致');
                    }
                    break;
                case BrandOrder::ORDER_TYPE_RENEW:
                    if ($brand_account['account_status'] != BrandAccountInfo::ACCOUNT_STATUS_USED) {
                        throw new \Exception('当前账户无法续费,请先开通');
                    }
                    if ($inStartTime <= $brand_account['in_end_time']) {
                        throw new \Exception('续费订单的入驻时间，必须大于当前套餐的入驻时间');
                    }
                    break;
            }

            if (!empty($result)) {
                \Doraemon\cache\EsUpdateCollector::multiInsertBrandIdsForWikiBasic([$brand_account['brand_id']]);
            }

            $packageInfo = BrandPackage::getInfoByPackType($packType);
            if (empty($packageInfo)) {
                throw new \Exception('选择不存在或则错误的套餐');
            }
            // 生成存根记录
            $dsn = OrderSN::createOrderSN($brand_account['uid']);
            $data = [
                'uid' => $brand_account['uid'],
                'brand_id' => $brand_account['brand_id'],
                'trade_proof' => $request['trade_proof'],
                'brand_sn' => $dsn,
                'other_sn' => $request['other_sn'],
                'amount' => $request['amount'],
                'pay_platform' => $request['pay_platform'],
                'admin_id' => Admin::user()->id,
                'add_time' => time(),
            ];
            mBrandStub::insert($data);

            // 生成订单记录
            $brand_info = mBrand::getInfo($brand_account['brand_id']);

            $order_data = [
                'dsn' => $dsn,
                'uid' => $brand_account['uid'],
                'brand_id' => $brand_account['brand_id'],
                'brand_name' => $brand_info['brand_name'],
                'package_id' => $packageInfo['id'],
                'package_name' => $packageInfo['package_name'],
                'identify' => $identify,
                'add_time' => time(),
                'order_status' => BrandOrder::ORDER_STATUS_FINISHED,
                'pay_platform' => $request['pay_platform'],
                'other_sn' => $request['other_sn'],
                'pay_time' => time(),
                'pay_status' => BrandOrder::PAY_STATUS_PAID,
                'amount' => $request['amount'],
                'product_price' => $packageInfo['price'],
                'price' => $packageInfo['discount_price'],
                'service_status' => BrandOrder::SERVICE_STATUS_FINISHED,
                'pack_type' => $packType,
                'admin_id' => Admin::user()->id,
                'in_start_time' => $inStartTime,
                'in_end_time' => $inEndTime
            ];
            switch ($orderType) {
                case BrandOrder::ORDER_TYPE_NEW:
                    if (BrandOrder::hasOrder($brand_account['brand_id'])) {
                        $order_data['order_type'] = BrandOrder::ORDER_TYPE_RENEW;
                    } else {
                        $order_data['order_type'] = BrandOrder::ORDER_TYPE_NEW;
                    }
                    break;
                case BrandOrder::ORDER_TYPE_UPGRADE:
                    $order_data['order_type'] = BrandOrder::ORDER_TYPE_UPGRADE;
                    break;
                case BrandOrder::ORDER_TYPE_RENEW:
                    $order_data['order_type'] = BrandOrder::ORDER_TYPE_RENEW;
                    break;
            }
            $isDelayedOrder = Order::isDelayedOrder($order_data);
            //延时订单，服务状态为未开通
            $order_data['service_status'] = $isDelayedOrder ? BrandOrder::SERVICE_STATUS_UNFINISHED : BrandOrder::SERVICE_STATUS_FINISHED;
            $orderId = BrandOrder::insertData($order_data);
            if ($order_data['in_start_time'] > date('Y-m-d')) {//延时订单
                //延时订单，不更新账户信息，到开始时间去更新
                RenewPackageService::createRenewPackage($brand_account['brand_id'], $order_data['package_id'], $orderId, $inStartTime, $inEndTime);
            } else {
                Order::afterStartBrandAccount($order_data);
                BrandRightsAllService::afterBrandOrder($order_data);
            }

            $success = new MessageBag([
                'title' => '添加付费订单成功'
            ]);
            return redirect('/admin/brand/account/index')->with(compact('success'));
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
    }

    public function qrcode(Request $request, Content $content, $id)
    {
        if (!Admin::user()->can('brand.pay')) {
            throw new \Exception('你没有该页面的权限');
        }
        $request = $request->all();
        if (isset($request['qrCode'])) {
            $accountInfo = BrandAccountInfo::getOneByWhere(['id' => $id]);
            $brandId = $accountInfo ? $accountInfo['brand_id'] : 0;
            $brandInfo = $brandId ? mBrand::getInfo($brandId) : [];
            $info = [
                'id' => $id,
                'uid' => $accountInfo['uid'],
                'brand_id' => $brandId,
                'brand_name' => $brandInfo['brand_name'],
                'pack_type_desc' => isset(BrandPackage::$packTypeDesc[$brandInfo['pack_type']]) ? BrandPackage::$packTypeDesc[$brandInfo['pack_type']] : '无',
                'qr_image' => $request['qrCode'],
            ];

            $form = new Form($info);
            $form->hidden('id');
            $form->text('uid', 'uid')->readonly()->setWidth(4, 2);
            $form->text('brand_id', '品牌id')->readonly()->setWidth(4, 2);
            $form->text('brand_name', '品牌名称')->readonly()->setWidth(4, 2);
            $form->display('qr_image', '支付码')->with(function ($value) {
                return "<img src='" . $value . "' width='400' height='487'>";
            })->help('右键->图片存储，保存支付码');
            return $content->header('生成支付码')
                ->breadcrumb(
                    ['text' => '品牌账户管理', 'url' => '/brand/account/index'],
                    ['text' => '生成支付码'],
                )->row($form->render());
        } else {
            $info = BrandAccountInfo::getOneByWhere(['id' => $id]);
            $uid = $info ? $info['uid'] : 0;
            $brandId = $info ? $info['brand_id'] : 0;
            $hasUnUsedOrder = 0;
            if ($uid) {
                $hasUnUsedOrderRes = BrandOrder::hasUnUsedOrder($uid);
                $hasUnUsedOrder = $hasUnUsedOrderRes[$uid];
            }
            if ($hasUnUsedOrder) {
                admin_toastr('该品牌已存在未生效的续费订单，无法再次续费。', 'warning', ['timeOut' => 5000, 'positionClass' => 'toast-bottom-right']);
                return back()->with();
            }

            $brandInfo = $brandId ? mBrand::getInfo($brandId) : [];
            if ($info && $brandInfo) {
                $info['brand_name'] = $brandInfo['brand_name'];
                $info['pack_type'] = $brandInfo['pack_type'];
                $info['pack_type_desc'] = isset(BrandPackage::$packTypeDesc[$brandInfo['pack_type']]) ? BrandPackage::$packTypeDesc[$brandInfo['pack_type']] : '无';
                //新开默认时间
                $startTime1 = date('Y-m-d');
                $info['in_start_time1'] = $startTime1;
                $info['in_end_time1'] = date('Y-m-d', strtotime('+365day', strtotime($startTime1)));
                $info['pack_type1'] = $info['pack_type'];
                //$info['identify1'] = $info['identify'];
                //升级默认时间
                $startTime2 = strtotime($info['in_start_time']) > 0 ? $info['in_start_time'] : date('Y-m-d');
                $endTime2 = strtotime($info['in_end_time']) > 0 ? $info['in_end_time'] : date('Y-m-d', strtotime('+365day', strtotime($startTime2)));
                $info['in_start_time2'] = $startTime2;
                $info['in_end_time2'] = $endTime2;
                $info['pack_type2'] = $info['pack_type'];
                //$info['identify2'] = $info['identify'];
                //续签默认时间
                $startTime3 = strtotime($info['in_end_time']) > 0 ? date('Y-m-d', strtotime('+1day', strtotime($info['in_end_time']))) : date('Y-m-d');
                $info['in_start_time3'] = $startTime3;
                $info['in_end_time3'] = date('Y-m-d', strtotime('+365day', strtotime($startTime3)));
                $info['pack_type3'] = $info['pack_type'];
                //$info['identify3'] = $info['identify'];

                $form = new Form($info);
                $form->hidden('id');
                $form->text('uid', 'uid')->readonly()->setWidth(4, 2);
                $form->text('brand_id', '品牌id')->readonly()->setWidth(4, 2);
                $form->text('brand_name', '品牌名称')->readonly()->setWidth(4, 2);
                $form->text('pack_type_desc', '当前套餐')->disable()->setWidth(4, 2);
                $defaultOrderType = $this->getDefaultOrderType($info);
                $whenOption = $this->getWhenOption($defaultOrderType);
                $form->select('order_type', '订单类型')->options(
                    $whenOption
                )->when(BrandOrder::ORDER_TYPE_NEW, function (Form $form) use ($info) {
                    $form->date('in_start_time1', '入驻开始时间')->setWidth(4, 2)->help("<span style='color: #ff0000'>请检查时间，必填</span>");
                    $form->date('in_end_time1', '入驻到期时间')->setWidth(4, 2)->help("<span style='color: #ff0000'>请检查时间，必填</span>");
                    $option = BrandService::getPackageOption($info['brand_id'], $info['pack_type']);
                    $help = [
                        '认证账号、认证套餐：为认证账号的套餐。',
                        '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;高级认证账号、高级认证简单套餐、高级认证套餐：为高级认证账号的套餐。',
                    ];
                    $form->select('pack_type1', '套餐')->options($option)->setWidth(6, 2)->help("<span style='color: #ff0000'>" . implode('<br/>', $help) . "</span>");;
                    //$form->text('identify1', '标识')->options($option)->setWidth(4, 2)->help("<span style='color: #ff0000'>必填</span>");
                })->when(BrandOrder::ORDER_TYPE_UPGRADE, function (Form $form) use ($info) {
                    $form->date('in_start_time2', '入驻开始时间')->setWidth(4, 2)->help("<span style='color: #ff0000'>请检查时间，必填</span>")->readonly();
                    $form->date('in_end_time2', '入驻到期时间')->setWidth(4, 2)->help("<span style='color: #ff0000'>请检查时间，必填</span>")->readonly();
                    $option = BrandService::getPackageOption($info['brand_id'], $info['pack_type']);
                    $help = [
                        '认证账号、认证套餐：为认证账号的套餐。',
                        '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;高级认证账号、高级认证简单套餐、高级认证套餐：为高级认证账号的套餐。',
                    ];
                    $form->select('pack_type2', '套餐')->options($option)->setWidth(6, 2)->help("<span style='color: #ff0000'>" . implode('<br/>', $help) . "</span>");;
                    //$form->text('identify2', '标识')->options($option)->setWidth(4, 2)->help("<span style='color: #ff0000'>必填</span>");
                })->when(BrandOrder::ORDER_TYPE_RENEW, function (Form $form) use ($info) {
                    $form->date('in_start_time3', '入驻开始时间')->setWidth(4, 2)->help("<span style='color: #ff0000'>请检查时间，必填</span>");
                    $form->date('in_end_time3', '入驻到期时间')->setWidth(4, 2)->help("<span style='color: #ff0000'>请检查时间，必填</span>");
                    $option = BrandService::getPackageOption($info['brand_id'], 0);
                    $help = [
                        '认证账号、认证套餐：为认证账号的套餐。',
                        '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;高级认证账号、高级认证简单套餐、高级认证套餐：为高级认证账号的套餐。',
                    ];
                    $form->select('pack_type3', '套餐')->options($option)->setWidth(6, 2)->help("<span style='color: #ff0000'>" . implode('<br/>', $help) . "</span>");;
                    //$form->text('identify3', '标识')->options($option)->setWidth(4, 2)->help("<span style='color: #ff0000'>必填</span>");
                })->setWidth(4)->default($defaultOrderType)->help("<span style='color: red'>请选择订单类型（开通、升级、续费）</span>");;
                $help = [
                    '开通套餐：请参考套餐价格。',
                    '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;升级套餐：(升级套餐-当前套餐)/365*(品牌到期时间-升级时间)；金额取整。',
                ];
                $form->decimal('amount', '支付金额')->setWidth(6, 2)->help("<span style='color: red'>" . implode('<br/>', $help) . "</span>")->required();
                $payPlatForm = mBrandStub::PAY_PLATFORM;
                unset($payPlatForm[mBrandStub::PAY_PLATFORM_OFFLINE]);
                $form->select('pay_platform', '付款类型')->options($payPlatForm)->setWidth(2, 2)->required();
                $form->textarea('remark', '备注')->required();
                $form->action('/admin/brand/pay/qrcode/' . $id);
            }

            return $content
                ->header('生成支付码')
                ->breadcrumb(
                    ['text' => '品牌账户管理', 'url' => '/brand/account/index'],
                    ['text' => '生成支付码'],
                )->row($form->render());
        }
    }

    public function postQrcode(Request $request, $id)
    {
        if (!Admin::user()->can('brand.pay')) {
            throw new \Exception('你没有该操作的权限');
        }
        try {
            $accountInfo = BrandAccountInfo::getOneByWhere(['id' => $id]);
            if (empty($accountInfo['uid'])) {
                throw new \Exception('请先给品牌绑定一个用户');
            }
            $brandId = $accountInfo ? $accountInfo['brand_id'] : 0;
            $brandInfo = $brandId ? mBrand::getInfo($brandId) : [];
            if (empty($accountInfo) || empty($brandInfo)) {
                throw new \Exception('不存在的账户信息');
            }
            $request = $request->all();
            $orderType = $request['order_type'];
            if (empty($orderType) || !isset(BrandOrder::ORDER_TYPE_MAP[$orderType])) {
                throw new \Exception('请选择订单类型');
            }
            if ($orderType == 1) {
                $inStartTime = $request['in_start_time1'];
                $inEndTime = $request['in_end_time1'];
                $packType = $request['pack_type1'];
                //$identify = $request['identify1'];
            } else if ($orderType == 2) {
                $inStartTime = $request['in_start_time2'];
                $inEndTime = $request['in_end_time2'];
                $packType = $request['pack_type2'];
                //$identify = $request['identify2'];
            } else if ($orderType == 3) {
                $inStartTime = $request['in_start_time3'];
                $inEndTime = $request['in_end_time3'];
                $packType = $request['pack_type3'];
                //$identify = $request['identify3'];
            }
            if (empty($inEndTime)) {
                throw new \Exception('请输入入驻结束时间');
            }
            if (empty($inStartTime) || empty($inEndTime)) {
                throw new \Exception('请选择入驻时间');
            }
            if (strtotime($inStartTime) >= strtotime($inEndTime)) {
                throw new \Exception('入驻结束时间必须大于入驻开始时间');
            }
            if ($orderType == 1 || $orderType == 3) {
                if (strtotime($inStartTime) < strtotime(date('Y-m-d'))) {
                    throw new \Exception('入驻开始时间不能小于当前时间');
                }
                if (strtotime($inEndTime) < strtotime(date('Y-m-d'))) {
                    throw new \Exception('入驻结束时间不能小于等于当前时间');
                }
            }
            if (empty($request['amount']) && $request['amount'] <= 0) {
                throw  new  \Exception('请输入支付金额');
            }
            if (empty($request['pay_platform']) || !in_array($request['pay_platform'], [mBrandStub::PAY_PLATFORM_ALI_PAY, mBrandStub::PAY_PLATFORM_WE_CHAT])) {
                throw  new  \Exception('请选择付款类型');
            }
            if (empty($request['remark'])) {
                throw  new \Exception('请出入备注信息');
            }

            $isNewPack = BrandService::isNewPack($packType);
            $packArr = $isNewPack ? BrandPackage::$newPackTypeList : BrandPackage::$packTypeList;
            if (empty($packType) && !in_array($packType, $packArr)) {
                throw  new  \Exception('请选择一个套餐');
            }

            $packageInfo = BrandPackage::getInfoByPackType($packType);
            if (empty($packageInfo)) {
                throw new \Exception('选择不存在或则错误的套餐');
            }
            switch ($orderType) {
                case BrandOrder::ORDER_TYPE_NEW:
                    break;
                case BrandOrder::ORDER_TYPE_UPGRADE:
                    if ($inStartTime != $accountInfo['in_start_time'] || $inEndTime != $accountInfo['in_end_time']) {
                        throw new \Exception('升级套餐的入驻时间和当前套餐时间必须一致');
                    }
                    break;
                case BrandOrder::ORDER_TYPE_RENEW:
                    if ($accountInfo['account_status'] != BrandAccountInfo::ACCOUNT_STATUS_USED) {
                        throw new \Exception('当前账户无法续费,请先开通');
                    }
                    if ($inStartTime <= $accountInfo['in_end_time']) {
                        throw new \Exception('续费订单的入驻时间，必须大于当前套餐的入驻时间');
                    }
                    break;
            }
            $packageId = $packageInfo['id'];
            $uid = $accountInfo['uid'];
            $pay_platform = $request['pay_platform'];//1:alipay,2:wechat
            $packType = $packType;
            $price = $request['amount'];
            $remark = $request['remark'];
            $adminId = Admin::user()->id;

            $orderDataType = 0;
            switch ($orderType) {
                case BrandOrder::ORDER_TYPE_NEW:
                    if (BrandOrder::hasOrder($accountInfo['brand_id'])) {
                        $orderDataType = BrandOrder::ORDER_TYPE_RENEW;
                    } else {
                        $orderDataType = BrandOrder::ORDER_TYPE_NEW;
                    }
                    break;
                case BrandOrder::ORDER_TYPE_UPGRADE:
                    $orderDataType = BrandOrder::ORDER_TYPE_UPGRADE;
                    break;
                case BrandOrder::ORDER_TYPE_RENEW:
                    $orderDataType = BrandOrder::ORDER_TYPE_RENEW;
                    break;
            }
            if (empty($orderDataType)) {
                throw new \Exception('订单类型错误');
            }

            list($order_sn, $package_name, $price) = Order::createOrder(
                $orderDataType,
                $uid,
                $brandId,
                $packageId,
                $pay_platform,
                $packType,
                $price,
                $inStartTime,
                $inEndTime,
                $remark,
                $adminId
            );
            $payStopTime = time() + 7200;
            Order::pay($uid, $order_sn, $pay_platform, $payStopTime);
            $payInfo = OrderPay::getPayInfoByOrderNo($order_sn, OrderPay::_PAY_ORDER_TYPE_BRAND);
            $payInfo = $payInfo ? array_shift($payInfo) : [];
            $qr_code_url = $payInfo ? stripslashes($payInfo['pay_order_info']) : '';
            $qr_code_url = str_replace('"', '', $qr_code_url);;
            if ($payInfo && $qr_code_url) {
                $payStopTime = date('Y.m.d H:i', $payStopTime);
                $qrCodeImageUrl = $this->createPayQrCode($qr_code_url, $price, mBrandStub::PAY_PLATFORM[$pay_platform], $payStopTime);
                if (empty($qrCodeImageUrl)) {
                    throw new \Exception('生成支付码图片失败，请重新生成');
                }
                return redirect('/admin/brand/pay/qrcode/' . $id . '?qrCode=' . $qrCodeImageUrl)->with(compact(new MessageBag([
                    'title' => '生成支付码成功'
                ])));
            } else {
                throw new \Exception('获取支付信息失败');
            }
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => $e->getMessage() . '。请重新生成。'
            ]);
            return back()->with(compact('error'));
        }
    }

    private function createPayQrCode($qrCodeUrl, $amount, $payWay, $payStopTime)
    {
        $qrCodeImage = '';
        $imageCreateInfo = mImageCreate::getByWhere(['title' => '品牌支付码', 'i_status' => mImageCreate::STATUS_PUBLISH]);
        if (empty($imageCreateInfo)) {
            throw new \Exception('不存在的模版');
        }
        $tId = $imageCreateInfo['id'];
        $params = [
            'https://img.haohaozhu.cn/Op-imageShow/b4ecc30xc14l0TB00qu0mfr?iv=1',//背景图
            $qrCodeUrl,//二维码
            '品牌服务套餐',//套餐描述
            '¥' . $amount,//金额
            '请在 ' . $payStopTime . ' 前完成支付',//支付截止时间
            $payWay . '扫码支付，如需开票请提前与商务经理沟通',//支付描述
        ];
        $result = ImageCreate::buildImageByTidAndParams($tId, $params, ImageCreate::OP_PIC_MODULE);
        if ($result['code'] && $result['url']) {
            $qrCodeImage = $result['url'];
        }
        return $qrCodeImage;
    }

    private function getDefaultOrderType($accountInfo)
    {
        $defaultOrderType = BrandOrder::ORDER_TYPE_NEW;
        if ($accountInfo['account_status'] != BrandAccountInfo::ACCOUNT_STATUS_USED) {
            $defaultOrderType = BrandOrder::ORDER_TYPE_NEW;
        } else if ($accountInfo['account_status'] == BrandAccountInfo::ACCOUNT_STATUS_USED || $accountInfo['in_end_time'] >= date('Y-m-d')) {
            $defaultOrderType = BrandOrder::ORDER_TYPE_UPGRADE;
        } else if ($accountInfo['account_status'] == BrandAccountInfo::ACCOUNT_STATUS_USED && BrandAccount::isBeforeExpire($accountInfo)) {//临期
            $defaultOrderType = BrandOrder::ORDER_TYPE_RENEW;
        }
        return $defaultOrderType;
    }

    private function getWhenOption($defaultOrderType)
    {
        $whenOption = BrandOrder::ORDER_TYPE_MAP;
        switch ($defaultOrderType) {
            case BrandOrder::ORDER_TYPE_NEW;
                unset($whenOption[BrandOrder::ORDER_TYPE_UPGRADE]);
                unset($whenOption[BrandOrder::ORDER_TYPE_RENEW]);
                break;
            case BrandOrder::ORDER_TYPE_UPGRADE:
                unset($whenOption[BrandOrder::ORDER_TYPE_NEW]);
                break;
        }
        return $whenOption;
    }
}
